<template>
  <div class="login">
    <van-cell-group inset>
      <van-field v-model="username" name="username" label="用户名" placeholder="用户名(至少八位)" :rules="[
          {
            message: '需包含大小写字母和数字且大于8位',
            pattern: usernamePattern,
          },
        ]" />
      <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码(需包含大小写和数字)" />
      <van-field v-model="repeatPassword" v-show="loginOrregister === false" type="password" name="repeatPassword"
        label="确认密码" placeholder="再次输入密码" />
      <van-field v-model="sms" v-show="loginOrregister === false" name="verify" center clearable label="验证码"
        placeholder="请输入验证码" autocomplete="off">
        <template #button>
          <div id="verify-img"></div>
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit" @click="submitHandle">
        提交
      </van-button>
    </div>
  </div>
</template>

<script>
import GVerify from "@/tool/verify.js";
import { nextTick, onMounted, reactive, toRefs, watch } from "vue";
import { post } from "@/tool/post";
import { Toast, Notify } from "vant";
import { debounce } from '@/tool/deboOrthro'

export default {
  props: {
    loginOrregister: {
      type: Boolean,
      default: true,
    },
  },
  name: "login_",
  setup(props, { emit }) {
    const usernamePattern = /^([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})|(\d+)|([a-zA-Z]+\d*)$/g;
    // const usernamePattern = /^[0-9|a-z|@|$|.|!|&|*]{8,}$/g;
    const state = reactive({
      username: "",
      sms: "",
      password: "",
      repeatPassword: "",
      loginOrregister: true,
    });
    let verifyCode = null;
    state.loginOrregister = props.loginOrregister;
    const onSubmit = () => {
      if (!state.username.match(usernamePattern)) {
        console.log(state.username);
        return Toast("账号需包含数字或字母且大于8位");
      }
      if (!state.password.match(/[0-9]+/)) {
        return Toast("需包含数字");
      }
      if (!state.password.match(/[a-z]+/)) {
        return Toast("需包含小写");
      }
      if (!state.password.match(/[A-Z]+/)) {
        return Toast("需包含大写");
      }
      if (state.password.length < 7) {
        return Toast("长度至少八位");
      }
      if (props.loginOrregister) {
        // console.log(state.username, state.password);
        post("/user/login", {
          password: state.password,
          username: state.username,
        }).then((res) => {
          if (res.code === 200) {
            localStorage.setItem(
              import.meta.env.VITE_APP_USERMSG,
              JSON.stringify(res.data.res)
            );
            localStorage.setItem(import.meta.env.VITE_APP_TOKEN, res.data.token);
            emit("callbackToken", res.data.token);
            return Toast("登录成功");
          } else if (res.code === 403) {
            return Toast(res.msg);
          }

        });
      } else {
        // console.log("register");
        if (state.password !== state.repeatPassword) {
          return Toast("两次密码不一致");
        }
        if (!verifyCode.validate(state.sms)) {
          return Toast("验证码错误");
        }
        post("/user/register", {
          password: state.password,
          username: state.username,
        }).then((res) => {
          if (res.code === 402) {
            Toast(res.msg);
          } else {
            Toast("注册成功");
            emit("callbackBool", true);
          }
        });
      }
    };
    const submitHandle = debounce(onSubmit, 500)
    watch(
      () => props.loginOrregister,
      (value) => {
        state.loginOrregister = value;
      }
    );
    onMounted(() => {
      Notify({
        type: "warning",
        message: "账号必须为数字哦~",
        duration: 3000,
      });
      nextTick(() => {
        verifyCode = new GVerify({
          id: "verify-img", //容器的ID
          type: "number", //图形验证码的类型：blend-数字字母混合类型（默认）、number-纯数字、letter-纯字母
        });
      });
    });
    return {
      ...toRefs(state),
      submitHandle,
      usernamePattern,
    };
  },
};
</script>

<style lang="less" scoped>
.login {
  margin-bottom: 40px;
}
</style>